﻿namespace VIT.BusinessLogicLayer.CRM
{
    using System.Collections.Generic;
    using System.Linq;

    using VIT.DataAccessLayer.CRM;
    using VIT.DataTransferObjects;

    public class AgentBLL : BLLBase
    {
        private readonly IAgentDAL _agentDAL;

        public AgentBLL(string connectionString = "")
            : base(connectionString)
        {
            this._agentDAL = new AgentDAL(this.DatabaseFactory);
        }

        public IList<string> GetAllDomainAgent()
        {
            var query = this._agentDAL.GetAll().Select(e => e.Domain);
            var data = query.ToList();
            return data;
        }

        public void SaveAgent(AgentConfigDto dto, string domain)
        {
            var obj = this._agentDAL.GetAll().FirstOrDefault(e => e.Domain == domain);
            if (obj == null)
            {
                obj = new Entity.CRM.Agent();
                this._agentDAL.Add(obj);
            }

            obj.Domain = domain;
            obj.FreeDay = dto.FreeDay;
            obj.ConnectionString = dto.Id;

            this.SaveChanges();
        }

        public AgentDto GetAgentByDomain(string domain)
        {
            var query = this._agentDAL.GetAll()
                .Where(e => e.Domain.ToLower() == domain.ToLower())
                .Select(e => new AgentDto
                {
                    AgentContactName = e.AgentContactName,
                    AgentCreateDate = e.AgentCreateDate,
                    AgentEmail = e.AgentEmail,
                    AgentPhone = e.AgentPhone,
                    AgentSkype = e.AgentSkype,
                    AgentYahoo = e.AgentYahoo,
                    ConnectionString = e.ConnectionString,
                    Id = e.Domain,
                    FreeDay = e.FreeDay
                });
            var data = query.FirstOrDefault();
            return data;
        }

        public void UpdateAgent(AgentDto dto)
        {
            var obj = this._agentDAL.GetById(dto.Id);
            if(obj != null)
            {
                obj.AgentContactName = dto.AgentContactName;
                obj.AgentEmail = dto.AgentEmail;
                obj.AgentPhone = dto.AgentPhone;
                obj.AgentSkype = dto.AgentSkype;
                obj.AgentYahoo = dto.AgentYahoo;

                this._agentDAL.Update(obj);
                this.SaveChanges();
            };
        }
    }
}
